//
//  ERanking.m
//  AppRanking
//
//  Created by Gang.Wang on 12-11-8.
//  Copyright (c) 2012年 Gang.Wang. All rights reserved.
//


#import "ERanking.h"
#import "mcf.h"
#import "JSONKit.h"

@implementation ERanking

@synthesize appName = appName_;
@synthesize rankingValues = rankingValues_;

@synthesize title = title_;
@synthesize subTitle = subTitle_;

@synthesize yAxisTitle = yAxisTitle_;

- (void) dealloc
{
    YRelease(appName_)
//    YRelease(rankingValues_)
    
    YRelease(title_)
    YRelease(subTitle_)
    
    YRelease(yAxisTitle_)
    
    [super dealloc];
}



- (id) initWithData:(NSData *) theData
{
    self = [super init];
    if (self)
    {
        NSMutableArray * temp_array = [[NSMutableArray alloc] init];
        
        self.rankingValues = temp_array;
        YRelease(temp_array);
        
        [self parseJsonData:theData];
    }
    return self;
}


- (void) parseJsonData:(NSData *) jsonData
{
    if (!jsonData)
    {
        return;
    }
    
    NSDictionary * dic = [jsonData objectFromJSONData];
    
    if ([NSDictionary isNilOrEmpty:dic])
    {
        return;
    }
    
    
    self.title = [[dic objectForKey:@"title"] objectForKey:@"text"];
    self.subTitle = [[dic objectForKey:@"subtitle"] objectForKey:@"text"];
    
    self.yAxisTitle = [[[dic objectForKey:@"yAxis"] objectForKey:@"title"] objectForKey:@"text"];
    
    
    NSArray * series = [dic objectForKey:@"series"];
    
    if ([NSArray isNilOrEmpty:series])
    {
        return;
    }
    
    self.appName = [[series objectAtIndex:0] objectForKey:@"name"];
    
    NSArray * rankData = [[series objectAtIndex:0] objectForKey:@"data"];
    
    for (id rankValueObj in rankData)
    {
        NSDictionary * rankDic = (NSDictionary *) rankValueObj;
        ERankingPoint * rankPoint = [[ERankingPoint alloc] init];
        
        rankPoint.yValue = [[rankDic objectForKey:@"y"] integerValue];
        rankPoint.name = [rankDic objectForKey:@"name"];
        
        [self.rankingValues addObject:rankPoint];
        YRelease(rankPoint);
    }
    
    
    NSDictionary * xAxis = [dic objectForKey:@"xAxis"];
    NSArray * categories = [xAxis objectForKey:@"categories"];
    
    int index_xAxis = 0;
    for (ERankingPoint * point in self.rankingValues)
    {
        if (index_xAxis < 0 ||
            index_xAxis >= [categories count])
        {
            continue;
        }
        
        point.xValue = [categories objectAtIndex:index_xAxis];
        index_xAxis++;
    }
}




@end






@implementation ERankingPoint

@synthesize name = name_;
@synthesize heightestRanking = heightestRanking_;

@synthesize lowestRanking = lowestRanking_;
@synthesize finalRanking = finalRanking_;

@synthesize yValue = yValue_;

- (void) dealloc
{
    YRelease(name_)
    
    [super dealloc];
}

@end